#include<string.h>
#include<stdio.h>
//#include<ctype.h>


void main(int argc, char *argv[])
{
  FILE *fpi, *fpo;
  unsigned char buf[512],boot[512];
  //int drive;

  printf("Make Linux boot sector utility.\n");
  printf("Designed by Felix.\n");

  if(argc!=3)
  {
    printf("Usage: makeboot filename /dev/hdxx");
    return;
  }

  fpi=fopen(argv[1],"rb");
  fpo=fopen(argv[2],"r+");
  if(!fpi)
  {
    printf("File %s not found.\n",argv[1]);
    return;
  }
 if(!fpo)
  {
    printf("File %s not found.\n",argv[2]);
    return;
  }


  if(fread(buf,1,512,fpi)!=512)
  {
    printf("File read error!\n");
    return;
  }
  fclose(fpi);

  if(buf[510]!=0x55 || buf[511]!=0xAA)
  {
    printf("File does not appear to be a boot record!\n");
    return;
  }
  if(memcmp(buf+0x36,"FAT16 ",6) && memcmp(buf+0x36,"FAT12 ",6))
  {
    printf("File format is not FAT16/FAT12\n");
    return;
  }
  if( *(short int *)(buf+0x0b) != 512 )
  {
    printf("File format error: not 512 bytes/sector\n");
    return;
  }
  if( *(short int *)(buf+0x0e) != 1 )
  {
    printf("File format error: may not be a normal boot record.\n");
    return;
  }

  if(fread(boot,1,512,fpo)!=512)
  {
    printf("Device read sector error.\n");
    return;
  }

  if(boot[510]!=0x55 || boot[511]!=0xAA)
  {
    printf("Error! invalid boot sector found on device!\n");
    return;
  }
  if(memcmp(boot+0x36,"FAT16 ",6) && memcmp(boot+0x36,"FAT12 ",6))
  {
    printf("Not FAT16/FAT12 drive!\n");
    return;
  }

  memcpy(boot,buf,11);
  memcpy(boot+0x3C,buf+0x3C,512-0x3C);
  boot[28]=0x3f;
  fseek(fpo,0,SEEK_SET);
  if(fwrite(boot,1,512,fpo)!=512)
  {
    printf("Device write sector error.\n");
    return;
  }

}


